﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace BgTransAPI.ControllerHelpers
{
    public class WebRequester
    {
        private string siteUrl;
        private string contentType;
        
        public WebRequester(string siteUrl, string contentType)
        {
            this.siteUrl = siteUrl;
            this.contentType = contentType;
        }

        public string SiteUrl
        {
            get
            {
                return this.siteUrl;
            }
            set
            {
                this.siteUrl = value;
            }
        }

        public string ContentType
        {
            get
            {
                return this.contentType;
            }
            set
            {
                this.contentType = value;
            }
        }

        public WebResponse PerformGetRequest(string urlParameters)
        {
            string fullUrl = urlParameters != null ? this.SiteUrl + urlParameters : this.SiteUrl;
            var request = WebRequest.Create(fullUrl) as HttpWebRequest;
            request.ContentType = this.contentType;
            request.CookieContainer = new CookieContainer();
            request.Method = "GET";
            
            WebResponse response = request.GetResponse();
            return response;
        }

        public WebResponse PerformPostRequest(string requestBody, CookieContainer cookie)
        {
            var request = WebRequest.Create(this.siteUrl) as HttpWebRequest;
            request.ContentType = this.contentType;
            request.Method = "POST";

            if (cookie != null)
            {
                request.CookieContainer = cookie;
            }

            if (requestBody != null)
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] bytes = encoding.GetBytes(requestBody);
                Stream newStream = request.GetRequestStream();
                newStream.Write(bytes, 0, bytes.Length);
                newStream.Close();
            }
            
            WebResponse response = request.GetResponse();
            return response;
        }
    }
}